<style lang="less" scoped>
// .search {
//   margin-left: 10px;
// }

.addsnForm {
  margin-bottom: 0;
}
.addsnForm /deep/.el-form-item__content .el-input {
  width: 320px !important;
}
.addsnForm /deep/.el-form-item__content .el-input + .el-button {
  margin-left: 20px;
}
/deep/.el-dialog__footer {
  padding-top: 0;
}
.manager_col {
  color: #409eff;
}
/deep/ .success-row {
  background: #f5f7fa !important;
}
</style>
<template>
  <div class="user_control">
    <el-form :model="userControl" :inline="true">
      <el-form-item label="用户名"> <el-input v-model.trim="userControl.username" placeholder="用户名" ></el-input> </el-form-item>
      <el-form-item label="邮箱"> <el-input v-model.trim="userControl.email" placeholder="邮箱" ></el-input> </el-form-item>
      <el-form-item label="已禁用 / 已启用">
        <el-select v-model="userControl.status" @change="userStatus_change">
          <el-option v-for="status in userControl.userStatus" :key="status.value" :value="status.status"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="时间节点">
        <el-date-picker
          v-model="user_date"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="创建日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          @change="changeDate"
        >
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="AK/SK">
        <el-input
          v-model.trim="userControl.aksk"
          placeholder="AK/SK"
          style="width: 150%"
        ></el-input>
      </el-form-item> -->
      <el-button type="primary" @click="onSearch" class="search"> <i class="el-icon-search"></i><span>查询</span></el-button>
      <el-button type="primary" @click="onDelete"> <i class="el-icon-delete"></i><span>批量删除</span></el-button>
      <el-button type="primary" @click="onExport"> <i class="el-icon-download"></i><span>导出</span></el-button>
    </el-form>
    <el-table :data="tableData" border @selection-change="handleSelectionChange" max-height="650" v-loading="table_loading" ref="multipleTable" :row-class-name="tableRowClassName">
      <template slot="empty"><i class="iconfont icon-kong"></i>暂无数据</template>
      <el-table-column width="50" type="selection" :selectable="userDisabled" fixed></el-table-column>
      <el-table-column label="序列" width="60"> <template v-slot="scope">{{ (scope.$index + pagingParams.size * (pagingParams.current - 1)) + 1 }}</template></el-table-column>
      <el-table-column label="用户名" width="220" prop="username">
        <template v-slot="scope">
          <div>{{ scope.row.username }} <span v-if="scope.row.type == 'manager'" class="manager_col" >( 超级管理员 )</span></div>
        </template>
        </el-table-column>
      <el-table-column label="邮箱" width="230" prop="email"></el-table-column>
      <el-table-column sortable label="创建时间" width="160" prop="createTime"></el-table-column>
      <el-table-column label="角色" width="90" prop="type"></el-table-column>
      <el-table-column label="状态" width="90" prop="status"></el-table-column>

      <!-- <el-table-column
        sortable
        label="修改时间" 
        width="200"
        prop="lastUpdateTime"
      ></el-table-column> -->
      <el-table-column label="AK" width="330" prop="appkey"></el-table-column>
      <el-table-column label="SK" width="330" prop="secret"></el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template v-slot="scope">
          <!-- <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button> -->
          <el-popconfirm confirmButtonText="确认"
            cancelButtonText="取消"
            :title="deleteTip"
            @onConfirm="handleDelete(scope.$index, scope.row)"
            style="margin-left: 5px"
            :iconColor="deleteColTip"
          >
            <el-button size="mini" type="danger" slot="reference" @click="deleteTip_handler(scope.$index, scope.row)">删除</el-button>
          </el-popconfirm>
          <el-switch
            v-if="username == scope.row.username ? false : true"
            style="margin-left: 10px"
            active-text="启用"
            inactive-text="禁用"
            v-model="userStatus[scope.$index].status"
            @change="changeUserStatus(scope.$index, scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagingParams['current']"
      :page-sizes="[10, 20, 40, 60, 80, 100, 200, 300, 400]"
      :page-size="pagingParams['size']"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagingParams['total']"
    ></el-pagination>
  </div>
</template>
<script>
import { adminSearch, adminDelete, adminUpdate } from "@/api/admin"
import moment from "moment"
import { pickerOptions } from '@/utils'
import { getUser, removeCookie } from '@/utils/auth'
export default {
  name: "userControl",
  data() {
    return {
      table_loading: false,
      userControl: {
        username: "",
        // aksk: "",
        email: "",
        status: "",
        userStatus: [
          {
            value: "enabled",
            status: "已启用",
          },
          {
            value: "disabled",
            status: "已禁用",
          },
          {
            value: "",
            status: "全部",
          },
        ],
      },
      // 日期
      pickerOptions: pickerOptions(),
      user_date: null,

      tableData: [],
      multipleSelection: [], //多选删除
      userStatus: [], //用户状态
      // 分页
      pagingParams: {
        username: "",
        email: "",
        // appkey: "",
        // secret:"",
        createDateFrom: "",
        createDateTo: "",
        current: 1, //默认当前页数为1
        size: 10,
        total: 0,
        status: "",
        // type:'0',
      },

      deleteTip: "确定要删除该用户吗？",
      deleteColTip: "",
      username: getUser().username,
    }
  },
  computed: {},
  methods: {
    changeDate() {
      let date = this.user_date,
        _d = this.pagingParams
      date && date.length
        ? ((_d.createDateFrom = moment(date[0]).format("YYYY-MM-DD")),
          (_d.createDateTo = moment(date[1]).format("YYYY-MM-DD")))
        : _d.createDateFrom = _d.createDateTo = null
    },
    userStatus_change() {
      let _s = this.userControl.status
      this.pagingParams.status =
        _s == "已启用" ? "enabled" : _s == "全部" ? "" : "disabled"
    },
    // ----------------------------查询-------------------------------------
    onSearch() {
      let params = this.pagingParams
      params.current = 1
      params.username = this.userControl.username
      params.email = this.userControl.email
      this.getUserList()
    },
    // ---------------------------获取用户列表-------------------------------
    getUserList() {
      let params = this.pagingParams
      this.table_loading = true
      adminSearch(this.pagingParams).then((res) => {
        params.size = res.data.size
        params.current = res.data.current
        params.total = res.data.total

        this.tableData = res.data.records
        this.table_loading = false

        //  转换status为Boolean
        let satatusArr = []
        this.tableData.map((x, index) => {
          satatusArr.push({
            status: x.status == "disabled" ? false : true,
          })
        })
        this.userStatus = satatusArr
      })
      // this.tableData = this.tableData.reverse()
    },
    // ------------------------------删除用户-------------------------------------
    deleteTip_handler(x, y) {
      if (this.username == y.username) {
        this.deleteTip = "确定永久删除自己的账户吗？删除后数据不可恢复，需重新注册！"
        this.deleteColTip = "red"
        sessionStorage.setItem("deletedManagerUser", this.username)
      } else {
        this.deleteTip = "确定要永久删除该用户吗？"
        this.deleteColTip = "rgb(255, 153, 0)"
        sessionStorage.removeItem("deletedManagerUser")
      }
    },
    handleDelete(x, y) {
      adminDelete({ datas: y.id }).then((res) => {
        if (res.code == 0 && res.data) {
          this.$message({
            message: res.msg,
            type: "success",
            durantion: 2 * 1000,
          })
         
          if (sessionStorage.getItem("deletedManagerUser")) {
            removeCookie('token')
            this.$router.go('/')
            sessionStorage.removeItem("deletedManagerUser")
          } else {
             this.getUserList()
          }
        } else {
          this.$message({
            message: "操作失败",
            type: "warning",
            durantion: 3 * 1000,
          })
        }
      })
    },
    // ---------------------------------批量删除用户-----------------------------------
    onDelete() {
      if (this.multipleSelection.length !== 0) {
        this.$confirm("此操作将永久删除已选用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
            for (let i = 0; i < this.multipleSelection.length; i++) {
              adminDelete({
                datas: this.multipleSelection[i].id,
              }).then((res) => {
                if (res.code == 0 && res.data) {
                   if(i + 1 >= this.multipleSelection.length) {
                  this.onSearch()
                  this.$message({
                   type: "success",
                   message: "删除成功!",
                 })
                  } 
                }
              })
            }
          }).catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            })
            this.$refs.multipleTable.clearSelection()
          })
      } else {
        this.$message({
          message: "请勾选要删除的用户",
          type: "warning",
          durantion: 3 * 1000,
        })
      }
    },
    //  -----------------------------设置用户状态(启用/禁用)------------------------------------------
    changeUserStatus(x, y) {
      let _this = this
      function status() {
        return y.status == "enabled" ? "disabled" : "enabled"
      }
      adminUpdate({ datas: y.id, status: status() }).then((res) => {
        if (res.code == 0 && res.data) {
          this.getUserList()
          if (y.status == "enabled") {
            this.$message({
              type: "success",
              message: "禁用成功",
            })
          } else {
            this.$message({
              type: "success",
              message: "启用成功",
            })
          }
        } else {
          this.$message({
            type: "error",
            message: "操作失败",
            durantion: 5 * 1000,
          })
        }
      })
    },
    //----------------------------- 禁止勾选自己账户--------------------------------------------------
    userDisabled(row, index) {
      return row.username == this.username ? 0 : 1
    },
    // 导出
    onExport() {},
    // 编辑
    handleEdit(index, row) {
      console.log(index, row)
    },
    // 分页
    handleSizeChange(val) {
      this.pagingParams.size = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.pagingParams.current = val
      this.getUserList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 高亮当前用户所在行
    tableRowClassName({ row, rowIndex }) {
      return row.username == this.username ? "success-row" : String
    },
  },
  created() {
    this.getUserList()
  },

}
</script>
